﻿using Devices;
using DevicesView.Entity;
using DevicesView.Logic.App;
using DevicesWPF.Logic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;


namespace DevicesView
{
    /// <summary>
    /// UCTestResult.xaml 的交互逻辑
    /// </summary>
    public partial class UCTestResult : UserControl
    {

        private List<Command> cmds;
        //private Logic.TestingsLogic logic = new Logic.TestingsLogic();
        private IDevices idev;
        private Action<UCTestResult, Command> saveCommandIng;
        private Action<UCTestResult, Command> deleteCommanded;

        public event Action<UCTestResult, Command> SaveCommandIng
        {
            add
            {
                saveCommandIng += value;
            }
            remove
            {
                saveCommandIng -= value;
            }
        }
        public event Action<UCTestResult, Command> DeleteCommanded
        {
            add
            {
                deleteCommanded += value;
            }
            remove
            {
                deleteCommanded -= value;
            }
        }

        public UCTestResult()
        {
            InitializeComponent();
            Logic.Test.ResultLogic resultLogic = new Logic.Test.ResultLogic();
            cmds = DevicesCollection.Commands;
            if (cmds == null)
                cmds = new List<Command>();

            if (resultLogic.Completed != null)
                cmds.AddRange(resultLogic.Completed.Select((r, c) => r.CMD));

            DataGridCMDS.ItemsSource = cmds;
        }

        public UCTestResult(IDevices device)
        {
            InitializeComponent();
            cmds = new List<Command>();
            idev = device;

            List<Command> copy = device.GetCommandes();
            if (copy != null)
                cmds.AddRange(copy);
            DataGridCMDS.ItemsSource = cmds;
        }


        public void RefreshData()
        {
        }


        public void AddCmds(Command cmd)
        {
            int index = cmds.FindIndex(o=>o.Result!=null);
            if (index >= 0)
                cmds.Insert(index,cmd);
            else
               cmds.Add(cmd);

            DataGridCMDS.ItemsSource = null;
            DataGridCMDS.ItemsSource = cmds;
            //gridControlCMD.RefreshDataSource();
        }
        public void RemoveCmds(Command cmd)
        {
            if (cmds.Remove(cmd))
            {
                DataGridCMDS.ItemsSource = null;
                DataGridCMDS.ItemsSource = cmds;
                if (idev != null && cmd.Status == 128)
                    idev.RemoveCommand(cmd.Id);
            }
        }
        public void SetResult(Result result)
        {
            if (idev == null || idev.CMDS==null || idev.CMDS.Count==0)
            {
                SetResultByCommand(result);
                return;
            }

            DevAutoConfigInfo info =DevicesLogic.GetDevicesTest(idev.Info.Code);
            if (info == null || !info.Selected || info.Tests==null|| info.Tests.Count == 0)
            {
                SetResultByCommand(result);
                return;
            }

            for (int i = idev.CMDS.Count-1; i >=0; i--)
            {
                if (idev.CMDS[i].Id==result.CMD.Id ||idev.CMDS[i].Name==result.CMD.Name || idev.CMDS[i].PetName != result.CMD?.PetName )
                    continue;
                DevicesTest test = info?.Tests?.FirstOrDefault(o=>o.Name==result.CMD.Name);
                if (test == null || test.Items == null || test.Items.Count == 0)
                    continue;

                Result newResult = new Result();
                newResult.CMD = idev.CMDS[i];
                newResult.Date = result.Date;
                newResult.Devices = result.Devices;
                newResult.Remarks = result.Remarks;
                newResult.ResultDatas = new List<ResultItem> { };
                newResult.Source = result.Source;
                newResult.Tag = result.Tag;
                newResult.Type = result.Type;
                foreach (var item in test.Items)
                {
                    ResultItem ri = result?.ResultDatas?.FirstOrDefault(o=>o.Code==item.Code);
                    if (ri != null)
                    {
                        newResult.ResultDatas.Add(ri);
                        result.ResultDatas.Remove(ri);
                    }
                }
                SetResultByCommand(newResult);
                idev.RemoveCommand(idev.CMDS[i].Id);
            }

            SetResultByCommand(result);
        }

        private void SetResultByCommand(Result result)
        {
            
            Command command = cmds?.FirstOrDefault(o => o.Id == result.CMD.Id);
            if (command != null)
            {
                command.Result = result;
                cmds.Remove(command);
                cmds.Add(command);
                DataGridCMDS.ItemsSource = null;
                DataGridCMDS.ItemsSource = cmds;
                DataGridCMDS.SelectedItem = command;
                SelectCommand();
            }
        }


        public bool SelectConnamd(Command cmd)
        {
            int index = cmds.IndexOf(cmd);
            if (index < 0)
                return false;
            DataGridCMDS.SelectedIndex = index;
            return true;
        }

        private void SelectCommand()
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                if (this.DataGridCMDS.SelectedItem != null)
                {
                    Command cmd = DataGridCMDS.SelectedItem as Command;
                    TestItems.Result = cmd.Result;
                }
                else
                {
                    TestItems.Result = null;
                }
            }));

        }

        private void DataGridResult_Selected(object sender, RoutedEventArgs e)
        {
            SelectCommand();
        }

        private void DataGridResult_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            SelectCommand();
        }
        /// <summary>
        /// 保存结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Command cmd = DataGridCMDS.SelectedItem as Command;
            if (cmd == null || cmd.Result == null)
                return;
            if (comboBoxEditDoc.SelectedItem == null)
            {
                BCL.WPFComponent.UCMessageBox.Show("请选择操作医生!");
                return;
            }

            cmd.Operator = (comboBoxEditDoc.SelectedItem as Doctor).Name;
            cmd.OperatorCode = (comboBoxEditDoc.SelectedItem as Doctor).Id.ToString();
            saveCommandIng?.Invoke(this, cmd);
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (AppResource.CurrentResource.Doctors != null)
            {
                comboBoxEditDoc.ItemsSource = AppResource.CurrentResource.Doctors;
                comboBoxEditDoc.DisplayMemberPath = "Name";
                Doctor info = AppResource.CurrentResource.Doctors.FirstOrDefault(o => o.Name == AppResource.CurrentResource.LoginUser?.UserName);
                if (info != null)
                    comboBoxEditDoc.SelectedItem = info;
            }
        }



        private void DataGridCMDS_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SelectCommand();
        }

        private void Border_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (column1.Width.Value == 0)
                column1.Width = new GridLength(5, GridUnitType.Star);
            else
                column1.Width = new GridLength(0, GridUnitType.Star);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Command cmd = DataGridCMDS.SelectedItem as Command;
            if (cmd == null)
                return;
            deleteCommanded?.Invoke(this, cmd);
        }

        /// <summary>
        ///  应用模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_MouseDown(object sender, MouseButtonEventArgs e)
        {

        }
    }

}
